import { mapState } from 'vuex'
import commonJs from '~/mixins/commonJs'
export default {
  computed: {
    ...mapState({
      locale: (state) => state.locale,
      exposureTime: (state) => state.exposureTime,
    }),
  },
  mixins: [commonJs],
  watch: {
    waitList: {
      handler(val) {
        if (this.visibletTimer) {
          clearTimeout(this.visibletTimer)
        }
        if (this.waitList.length > 0) {
          this.visibletTimer = setTimeout(() => {
            this.visibleCa()
          }, 300)
        }
      },
      deep: true,
      immediate: true,
    },
    exposureTime(val) {
      if (val) {
        this.$nextTick(() => {
          this.observeElements()
        })
      }
    },
    $route: {
      handler(newRoute, oldRoute) {
        if (process.browser) {
          if (
            newRoute &&
            oldRoute &&
            (newRoute.name !== oldRoute.name ||
              (newRoute.name === oldRoute.name &&
                JSON.stringify(newRoute.params) !==
                  JSON.stringify(oldRoute.params)))
          ) {
            this.initTrackExposure()
          }
        }
      },
      deep: true,
      immediate: true,
    },
  },
  data() {
    return {
      completedList: [],
      waitList: [],
      toolItems: [],

      observer: null,

      visibletTimer: null,

      scrollTimer: null,
    }
  },
  created() {
    this.completedList = []
    this.waitList = []
    this.toolItems = []
    this.observer = null
    this.visibletTimer = null
    this.scrollTimer = null
  },
  mounted() {
    this.initTrackExposure()
  },
  methods: {
    initTrackExposure() {
      // 组件销毁时停止观察
      if (this.observer) {
        this.observer.disconnect()
      }
      if (this.visibletTimer) {
        clearTimeout(this.visibletTimer)
      }
      if (this.scrollTimer) {
        clearTimeout(this.scrollTimer)
      }
      this.completedList = []
      this.waitList = []
      this.toolItems = []
      window.removeEventListener('scroll', this.handleVisibleScroll, false)
      this.$nextTick(() => {
        this.observeElements()
        window.addEventListener('scroll', this.handleVisibleScroll)
      })
    },
    visibleCa() {
      //console.log(this.waitList)
      try {
        let page = this.getCurPageName()
        let browserName = this.getBroswer()
        let deviceType = this.getDeviceType()
        const userLanguage = navigator.language || navigator.userLanguage
        let details = []
        this.waitList.forEach((item) => {
          if (
            page === item.page &&
            (page !== '分类页' ||
              (page === '分类页' &&
                item.page_position.indexOf('#Just launched') === -1))
          ) {
            details.push({
              page_position: item.page_position,
              tool_handle: item.tool_handle,
              advertisement_id: item.advertisement_id,
            })
          }
        })
        let req = {
          page_name: page,
          url: window.location.href,
          referer: document.referrer || null,
          page_language: this.locale,
          browser_language: userLanguage,
          browser: browserName,
          version: process.env.version || null,
          device_type: deviceType,
          details: JSON.parse(JSON.stringify(details)),
        }
        this.$axiosApi.postEa(req)
        this.waitList = []
      } catch (error) {
        this.loadError()
      }
    },
    handleVisibleScroll() {
      if (this.scrollTimer) {
        clearTimeout(this.scrollTimer)
      }
      if (this.observer) {
        this.observer.disconnect()
      }
      // 设置一个延迟执行的定时器
      this.scrollTimer = setTimeout(() => {
        this.observeElements()
      }, 300)
    },
    observeElements() {
      // 创建 Intersection Observer 实例
      this.observer = new IntersectionObserver((entries) => {
        entries.forEach(
          (entry) => {
            if (
              entry.isIntersecting &&
              entry.intersectionRatio >= 0.5 &&
              entry.time >= 300
            ) {
              // 目标元素进入可视区域
              //console.log('在可视区域内:', entry.target.dataset)
              let dataset = entry.target.dataset
              if (!this.hasRealVal(dataset.visible)) {
                // 页面位置
                let toolPositionRes = ''
                if (dataset.page_position) {
                  toolPositionRes = `#${dataset.page_position}`
                } else {
                  toolPositionRes = dataset.position
                  if (
                    this.hasRealVal(dataset.issearch) &&
                    parseInt(dataset.issearch) === 1
                  ) {
                    toolPositionRes = 'Search list'
                  }
                  let index = this.hasRealVal(dataset.index)
                    ? String(parseInt(dataset.index) + 1).padStart(2, '0')
                    : 0
                  toolPositionRes = `#${toolPositionRes} - ${index}`
                }

                if (!this.completedList.includes(dataset.handle)) {
                  this.waitList.push({
                    page: this.getCurPageName(),
                    page_position: toolPositionRes,
                    tool_handle: dataset.handle,
                    advertisement_id: dataset.advertisement_id
                      ? dataset.advertisement_id
                      : null,
                  })
                  this.completedList.push(dataset.handle)
                }
                //设置为已展示
                entry.target.setAttribute('data-visible', 1)
              }
            }
          },
          { threshold: 0.5, rootMargin: '0px' }
        )
        //console.log(this.waitList)
      })

      // 获取所有具有 class="tool-item" 的 DOM 节点
      this.toolItems = document.querySelectorAll('.tool-dom')

      // 遍历每个节点，将其添加到 Intersection Observer 中进行观察
      this.toolItems.forEach((toolItem) => {
        this.observer.observe(toolItem)
      })
    },
  },
  beforeDestroy() {
    // 组件销毁时停止观察
    if (this.observer) {
      this.observer.disconnect()
    }
    if (this.visibletTimer) {
      clearTimeout(this.visibletTimer)
    }
    if (this.scrollTimer) {
      clearTimeout(this.scrollTimer)
    }
    window.removeEventListener('scroll', this.handleVisibleScroll, false)
  },
}
